<template>
  <div class="statisticsListPage h100">
    <!-- FOTA异常统计标题及搜索 -->
    <div class="statisticsListSearch">
      <div class="statisticsListSearchCont">
        <a-row :gutter="[10, 0]">
          <!-- 车型 -->
          <a-col :xs="12" :sm="12" :md="12" :lg="12" :xl="4" :xxl="5">
            <!-- <car-model-select
              :query="{ time: 0 }"
              :defaultValue="queryParams.modelIds"
              :maxTagCount="1"
              @changeoption="selectCarModel"
              :hasAll="false"
              :clear="true"
              style="width:100%;"
              mode="multiple">
            </car-model-select>-->
              <!-- <filter-box-collection
                :queryParam="queryParamsDesc"
                :placeholder="$t('pleaseSelect') +$t('vehicleModel')"
                @removetag="removeQueryKey"
                @search="searchData"
              >
                <template slot> -->
                  <!-- 车型 -->
                    <car-model-code-select
                      mode="default"
                      :query="{ time:instantUpdateTime, selectAll: false}"
                      :has-all="false"
                      :clear="true"
                      v-model="queryParams.modelCode"
                      @changeoption="(val,item) => {queryParamsDesc.modelCode = item ? item.showName : undefined;}"
                      style="width:100%;margin-bottom:10px"
                      @change="searchData"
                    ></car-model-code-select>
                  <!-- 款型 -->
                    <!-- <car-model-select
                      ref="carModelSelect"
                      mode="default"
                      :query="{time:instantUpdateTime, code: queryParams.modelCode}"
                      :has-all="false"
                      :default-value="queryParams.modelIds"
                      :clear="true"
                      style="width:100%;"
                      @changeoption="changeModels"
                    ></car-model-select>
                </template>
              </filter-box-collection> -->
          </a-col>
          <!-- VIN -->
          <a-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="4"
            :xxl="5">
            <a-input
              :placeholder="$t('pleaseInput') + 'VIN'"
              size="small"
              v-model="queryParams.vin"
              @keyup.enter="searchData"
              :allow-clear="true"/>
          </a-col>
          <!-- 任务名称 -->
          <a-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="7"
            :xxl="6">
            <a-input
              size="small"
              :placeholder="$t('pleaseInput') + $t('campaignName').toLowerCase()"
              :allow-clear="true"
              @keyup.enter="searchData"
              v-model="queryParams.taskName" />
          </a-col>
          <a-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="7"
            :xxl="7" >
            <div class="searchBtns">
              <a-button-group>
                <auth-button type="primary" :auth="statisticsPerms.clientLog.view" @click="searchData">
                  <i class="iconfont icon-chazhao"/>{{ $t('inquiry') }}
                </auth-button>
                <a-button @click="clearCondition">
                  <i class="iconfont icon-qingkong"/>{{ $t('clear') }}
                </a-button>
              </a-button-group>
              <!-- 导出明细 -->
              <auth-button
                type="primary"
                :loading="exportingDetail"
                :auth="statisticsPerms.clientLog.export"
                @click="exportDetail">
                <i class="iconfont icon-xiazai"/>{{ $t('exportDetail') }}
              </auth-button>
              <!-- 导出分布 -->
              <auth-button
                type="primary"
                :loading="exportingDistribute"
                :auth="statisticsPerms.clientLog.distributeExport"
                @click="exportDistribute"
                class="lastExportBtn">
                <i class="iconfont icon-xiazai"/>{{ $t('exportDistribute') }}
              </auth-button>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>

    <div class="statisticsListMain">
      <!-- FOTA异常统计表格列表 -->
      <div class="statisticsListMainLeft">
        <s-table
          ref="table"
          size="default"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          :scrollX="1100"
          class="h100">
          <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
            <table-ellipsis :text="text" :key="column.key"></table-ellipsis>
          </template>
          <template #reportingTime="text">
            <table-ellipsis :text="$commonFun.getDateMinuteStr(text)"></table-ellipsis>
          </template>
          <template #modelCode="text, record">
            <table-ellipsis :text="record.model ? record.model.code : '-'"></table-ellipsis>
          </template>
          <template #modelName="text, record">
            <table-ellipsis :text="record.model ? record.model.name : '-'"></table-ellipsis>
          </template>
          <!-- 版型 -->
          <template #stereotype="text, record">
            <table-ellipsis :text="record.model ? record.model.trimLevel : '-'"></table-ellipsis>
          </template>
          <template slot="operation" slot-scope="text, record">
            <!-- <auth-button
              type="primary"
              :ghost="true"
              size="small"
              v-if="record.file && record.file.id"
              :auth="statisticsPerms.clientLog.download"
              @click="downloadFile(record.file)"><i class="iconfont icon-xiazai"/>{{ $t('downLog') }}</auth-button>
            <span v-else>-</span> -->
            <span class="tableOperateSty" style="display: flex;">
              <auth-button
                type="primary"
                :ghost="true"
                size="small"
                @click="ecuListDetail(record)"><i class="iconfont icon-yanjing"/>查看</auth-button>
              <auth-button
                type="primary"
                :ghost="true"
                size="small"
                @click="showEcuExceptionDetail(record)">异常日志</auth-button>
            </span>
          </template>
        </s-table>
      </div>
      <!-- 升级异常车型分布 -->
      <div class="statisticsListMainRight">
        <full-parent-dom-with-dask :loading="loadingModelStatisticsData"></full-parent-dom-with-dask>
        <h4 class="">{{ $t('distribution') }}</h4>
        <ul class="modelExceptionCountLists">
          <li class="modelExceptionCountListItem" v-for="model in modelStatisticsData" :key="model.id">
            <span class="modelExceptionCountListItemText">
              <table-ellipsis :text="model.modelInfo"></table-ellipsis>
            </span>
            <span class="modelExceptionCountListItemNum">
              <table-ellipsis :text="model.count"></table-ellipsis>
            </span>
          </li>
          <li v-if="modelStatisticsData.length === 0" class="modelExceptionCountListItem">{{ $t('noData') }}</li>
        </ul>
        <div class="exceptionIndexPagination">
          <a-pagination
            v-show="totalCount"
            simple
            :current="pageInfo.pageNo"
            :total="totalCount"
            :pageSize="pageInfo.pageSize"
            @change="changePageSize" />
        </div>
      </div>
    </div>
    <!-- 异常日志 -->
    <part-update-exception-log-dialog
      ref="partUpdateExceptionLogDialog"
      height="60vh"
      width="60%"
      :query="exceptionDialogQuery"
      :title="logTitle"
      compt="showCarLog"
      :packageFile="packageFile"
    ></part-update-exception-log-dialog>
  </div>
</template>

<script>
import PartUpdateExceptionLogDialog from '@/views/components/PartUpdateExceptionLog/dialog.vue'
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import CarModelSelect from '@/views/components/CarModelSelect'
import { fotaExceptionColumns } from './config/list'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { STable } from '@/components'
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import logApi from '@/api/modules/log'
import fileApi from '@/api/modules/system/fileUpload'
import { downloadBlobFile } from '@/utils/functions'
import AuthButton from '@/components/AuthButton'
import AuthText from '@/components/AuthText'
import { statisticsPerms } from '@/config/permission/index'
import { mapState } from 'vuex'
const initQueryParams = {
  vin: '',
  taskName: '',
  // 车型
  modelCode:undefined,
  modelIds: undefined
}
export default {
  components: {
    PartUpdateExceptionLogDialog,
    FilterBoxCollection,
    CarModelCodeSelect,
    CarModelSelect,
    STable,
    TableEllipsis,
    FullParentDomWithDask,
    AuthButton,
    AuthText
  },
  data () {
    return {
      packageFile: {},
      logTitle: '',
      // 查看异常日志的搜索条件
      exceptionDialogQuery: null,
      statisticsPerms,
      exporting: false,
      columns: fotaExceptionColumns,
      queryParams: {
        ...initQueryParams
      },
      // 升级异常车型分布数据
      modelStatisticsData: [],
      loadingModelStatisticsData: true,
      pageInfo: {
        pageSize: 14,
        pageNo: 1
      },
      totalCount: 0,
      exportingDetail: false,
      exportingDistribute: false,
      queryParamsDesc: { ...initQueryParams },
      selectObj: {
        modelIds: {
          fetch: 'getModelName',
          data: null
        }
      },
    }
  },
  computed: {
    commonColumns () {
      return this.columns.filter(item => !item.special)
    },
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
    })
  },
  created () {
    this.getModelstatisticsData()
  },
  methods: {
    searchData () {
      this.refreshData()
      this.getModelstatisticsData()
    },
    clearCondition () {
      this.queryParams = { ...initQueryParams }
      this.queryParamsDesc={ ...initQueryParams }
      this.searchData()
    },
    selectCarModel (val) {
      this.queryParams.modelIds = val
    },
    // 修改车型
    changeModels(val) {
      this.queryParams.modelIds = val
      this.queryVehicleVersionTime = Date.now()
      this.queryParamsDesc.modelIds = this.getModelName(val)
      console.log('81813813813', 'this.queryParamsDesc.modelIds')
    },
    // 删除搜索框中已选择的条件
    removeQueryKey(key) {
      console.log(key)

      if (this['remove' + key + 'Query']) {
        this['remove' + key + 'Query']()
      } else {
        this.queryParams[key] = undefined
        this.queryParamsDesc[key] = undefined
      }
    },
    changeOption1(val, key) {
      this.queryParams[key] = val
      this.queryParamsDesc[key] = val
    },
    // 获取车型名称
    getModelName(val) {
      console.log(val, 'val')
      if (this.selectObj.modelIds.data === null) {
        this.selectObj.modelIds.data = this.transfterArrayToObj(this.$refs.carModelSelect.modelOptions, 'id', 'name')
      }
      return this.selectObj.modelIds.data[val] || ''
    },
    transfterArrayToObj(arr, id, value) {
      const obj = {}
      arr.forEach(item => {
        obj[item[id]] = item[value]
      })
      return obj
    },
    // 导出明细
    exportDetail () {
      this.exportingDetail = true
      logApi.exportClientLog(this.queryParams).then(res => {
        downloadBlobFile(res, this.$t('logDetail') + '.xlsx')
      }).finally(() => {
        this.exportingDetail = false
      })
    },
    // 导出分布
    exportDistribute () {
      this.exportingDistribute = true
      logApi.exportClientLogModelStatistics(this.queryParams).then(res => {
        downloadBlobFile(res, this.$t('updateExceptionModelDistribute') + '.xlsx')
      }).finally(() => {
        this.exportingDistribute = false
      })
    },
    loadData (parameter) {
      return logApi.getClientLog({ ...this.queryParams, ...parameter })
    },
    refreshData (isToFirstPage = true) {
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.table.loadData(obj)
    },
    // 获取升级异常车型分布
    getModelstatisticsData () {
      const params = {
        ...this.queryParams
      }
      this.modelstatisticsData = []
      this.loadingModelStatisticsData = true
      logApi.getClientLogModelStatistics(params).then(res => {
        if (!res.data) {
          return
        }
        this.modelStatisticsData = res.data.map(item => {
          const { model } = item
          let modelInfo = model.code
          if (model.name) {
            modelInfo += '[' + model.name + ']'
          }
          if (model.trimLevel) {
            modelInfo += '[' + model.trimLevel + ']'
          }
          return {
            id: item.modelId,
            modelInfo,
            count: item.count
          }
        })
      }).finally(() => {
        this.loadingModelStatisticsData = false
      })
    },
    changePageSize (page) {
      this.pageInfo.pageNo = page
      this.loadData()
    },
    // 下载日志
    downloadFile (file) {
      fileApi.downloadFileToLocal({ id: file.id }).then((res) => {
        downloadBlobFile(res, file.name)
      })
    },
    // 查看异常日志showEcuExceptionDetail
    showEcuExceptionDetail (record) {
      this.exceptionDialogQuery = {
        vehicleId: record.vehicleId,
        taskIds: record.taskId
      }
      this.packageFile=record.file
      this.logTitle=record.file.name
      this.$nextTick(() => {
        this.$refs.partUpdateExceptionLogDialog.switchVisible(true)
      })
    },
    ecuListDetail(record){
      console.log(record)
      var param = {
          "vin" : record.vin,
          "batchId" : record.batchId,
          "date": new Date().getTime()
      }
      this.$router.push({path:"/statistics/monitorList/detail","query":{
        "vin":record.vin,
        "batchId":record.batchId,
        "checkSeqNo":record.checkSeqNo,
        "taskId":record.taskId,
        "processId":record.processId,
        "taskName":record.taskName
      }})
      return
    },
  }
}
</script>
<style lang="less" scoped>
.statisticsListPage {
  display: flex;
  flex-direction: column;

  .statisticsListSearch {
    flex: none;
    display: flex;
    padding: 20px 24px 10px 24px;
    border-bottom: 1px solid @borderColor;

    .title18 {
      flex: none;
      margin-right: 120px;
    }

    .statisticsListSearchCont {
      flex: 1 0 0;
    }

  }

  .statisticsListMain {
    flex: 1 0 0;
    overflow: hidden;
    display: flex;

    .statisticsListMainLeft {
      flex: 1 0 0;
      padding: 20px 24px;
      overflow: hidden;
    }

    .statisticsListMainRight {
      position: relative;
      flex: 290px 0 0;
      border-left: 1px solid @borderColor;
      padding: 20px 10px;
      display: flex;
      flex-direction: column;

      >h4 {
        font-weight: bold;
        font-size: 1.1em;
        margin-bottom: 5px;
        flex: none;
      }
    }

    // 升级异常车型分布
    .modelExceptionCountLists {
      flex: 1 0 0;
      min-height: 200px;

      .modelExceptionCountListItem {
        display: flex;
        justify-content: space-between;
        line-height: 40px;
      }

      .modelExceptionCountListItemText {
        flex: 190px 0 0;
      }

      .modelExceptionCountListItemNum {
        width: 50px;
        flex: none;
        text-align: right;
      }
    }

    .exceptionIndexPagination {
      flex: none;
      margin-top: 10px;
    }
  }
}
</style>
<style lang="less">
.statisticsListSearchCont {
  .disabledAuthButtonWrap:nth-last-child(1) {
    margin-right: 0;
  }
  .ant-select-selection--multiple {
    max-height: 33px;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
